﻿using AspDemo.Models;
using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;

namespace AspDemo.Controllers
{
    [Route("api/user")]
    public class UserController : Controller
    {
        private readonly ApplicationDataContext _dbContext;
        public UserController(ApplicationDataContext dataContext)
        {
            _dbContext = dataContext;
        }

        [HttpPost("register")]
        public ApiResponse Register(
            [Required][FromForm]string name, 
            [Required][RegularExpression(@"^(?![0-9]+$)(?![a-zA-Z]+$)[0-9A-Za-z]{6,20}$")][FromForm]string password)
        {
            var userQuerry = from user in _dbContext.Users
                             where user.Name == name
                             select user;
            if (userQuerry.Any())
            {
                return new(ApiCode.Error, "用户名已注册", ApiResponse.NullData);
            }

            _dbContext.Users.Add(new Models.User
            {
                Name = name,
                SecretMd5 = GenerateMD5(Salt(password))
            });

            _dbContext.SaveChanges();

            return new(ApiCode.Success, "注册成功", ApiResponse.NullData);
        }

        [HttpPost("login")]
        public ApiResponse Login(
            [Required][FromForm] string name,
            [Required][RegularExpression(@"^(?![0-9]+$)(?![a-zA-Z]+$)[0-9A-Za-z]{6,20}$")][FromForm] string password)
        {
            var userQuerry = from user in _dbContext.Users
                             where user.Name == name
                             select user;
            if (!userQuerry.Any())
            {
                return new(ApiCode.Error, "用户不存在", ApiResponse.NullData);
            }
            if(userQuerry.First().SecretMd5 != GenerateMD5(Salt(password)))
            {
                return new(ApiCode.Error, "密码错误", ApiResponse.NullData);
            }
            return new ApiResponse(ApiCode.Success, "登陆成功", new
            {
                UserId = userQuerry.First().UId
            });
        }

        private static string GenerateMD5(string txt)
        {
            using (MD5 mi = MD5.Create())
            {
                byte[] buffer = Encoding.Default.GetBytes(txt);
                //开始加密
                byte[] newBuffer = mi.ComputeHash(buffer);
                StringBuilder sb = new StringBuilder();
                for (int i = 0; i < newBuffer.Length; i++)
                {
                    sb.Append(newBuffer[i].ToString("x2"));
                }
                return sb.ToString();
            }
        }

        private static string Salt(string str)
        {
            return str + "kjBAJGHKaknI=.";
        }
    }
}
